#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <memory>

namespace wzh
{
    class server_udp
    {
    public:
        server_udp(const int& port = 8080)
            :_port(port) {}
        ~server_udp()
        {
            close(_sock);
        }
        
        void Initserver()
        {
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);
            server.sin_addr.s_addr = INADDR_ANY;
            server.sin_family = AF_INET;
            server.sin_port = htons(_port);
            if(bind(_sock, (sockaddr*)&server, sizeof server) < 0)
            {
                perror("bind fail\n");
                exit(-1);
            }

        }

        void startserver()
        {
            char buffer[1024];
            while(1)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
                if(n > 0) buffer[n] = '\0';
                else continue;

                std::cout << "get message " << buffer << std::endl;
                sendto(_sock, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, sizeof(peer));
            }
        }

    private:
        int _port;
        int _sock;
    };
}
